import os
import sys
import time
from traceback import print_tb
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import threading
import ast
from NewBuildingOperator import NewBuildingOperator
from PageOperator import PageOperator
from LoginManager import LoginManager
from LoginAutoTimer import LoginAutoTimer

def parse_config(filename):
    config = {}
    with open(filename, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    current_key = None
    list_buffer = []
    dict_buffer = []
    in_list = False
    in_dict = False

    for line in lines:
        line = line.strip()

        if not line:
            continue

        if '=' in line and not in_list and not in_dict:
            key, value = map(str.strip, line.split('=', 1))
            if value.startswith('['):
                current_key = key
                list_buffer = [value]
                in_list = True
                if value.endswith(']'):
                    in_list = False
                    list_str = ' '.join(list_buffer).replace('\\', '')
                    config[current_key] = ast.literal_eval(list_str)
            elif value.startswith('{'):
                current_key = key
                dict_buffer = [value]
                in_dict = True
                if value.endswith('}'):
                    in_dict = False
                    dict_str = ' '.join(dict_buffer).replace('\\', '')
                    config[current_key] = ast.literal_eval(dict_str)
            else:
                if value.lower() in ('true', 'false'):
                    config[key] = value.lower() == 'true'
                elif value.isdigit():
                    config[key] = int(value)
                else:
                    config[key] = value.strip('"')
        elif in_list:
            list_buffer.append(line)
            if line.endswith(']'):
                in_list = False
                list_str = ' '.join(list_buffer).replace('\\', '')
                config[current_key] = ast.literal_eval(list_str)
        elif in_dict:
            dict_buffer.append(line)
            if line.endswith('}'):
                in_dict = False
                dict_str = ' '.join(dict_buffer).replace('\\', '')
                config[current_key] = ast.literal_eval(dict_str)

    return config

def get_config_path():
    # 获取当前执行文件的路径
    current_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
    # 构造config.txt文件的路径
    config_path = os.path.join(current_dir, "config.txt")
    return config_path

config_path = get_config_path()
config = parse_config(config_path)
interval = config['interval']
max_runs = config['max_runs']
game_login_url = config['game_login_url']
username = config['username']
password = config['password']
village_urls = config['village_urls']
building_urls = config['building_urls']
build_sequence = config['build_sequence']
resource_urls = config['resource_urls']

print(f"每次运行后等待时间: {interval}秒钟")
print(f"本次操作运行次数: {max_runs}")
print(f"登录地址: {game_login_url}")
print(f"账号: {username}")
print(f"密码: {password}")
print(f"密码: {'*' * len(str(password))}")
print(f"村庄资源页数量: {len(village_urls)}")
print(f"建筑页面数量: {len(building_urls)}")
print(f"建筑序列条目: {build_sequence}")
print(f"资源URL配置: {resource_urls}")



if __name__ == "__main__":
    config_path = get_config_path()
    config = parse_config(config_path)
    game_login_url = config.get("game_login_url")
    username = config.get("username")
    password = config.get("password")
    village_urls = config.get("village_urls")
    building_urls = config.get("building_urls")
    build_sequence = config.get("build_sequence")
    interval = config.get("interval", 300)
    max_runs = config.get("max_runs", 50)

    resource_urls = {
        f"resource_ID{i:02}_page": f"https://ts1.x1.asia.travian.com/build.php?id={i}"
        for i in range(1, 19)
    }

    timer = LoginAutoTimer(game_login_url, username, password, village_urls, resource_urls, building_urls, build_sequence, interval, max_runs)
    timer.start()